import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

import { 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  InputNumber, 
  Switch, 
  message, 
  Popconfirm,
  Card,
  Tag,
  Select,
  Transfer
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { api } from '../utils/api';

const { TextArea } = Input;
const { Option } = Select;

interface Exam {
  id: number;
  title: string;
  description: string;
  total_score: number;
  pass_score: number;
  time_limit: number;
  question_count: number;
  is_active: boolean;
  created_at: string;
}

interface Question {
  id: number;
  title: string;
  type: string;
  difficulty: string;
  category: {
    name: string;
  };
}

const ExamManagement: React.FC = () => {
  const [exams, setExams] = useState<Exam[]>([]);
  const [questions, setQuestions] = useState<Question[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [previewModalVisible, setPreviewModalVisible] = useState(false);
  const [editingExam, setEditingExam] = useState<Exam | null>(null);
  const [previewingExam, setPreviewingExam] = useState<Exam | null>(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  const navigate = useNavigate();


  useEffect(() => {
    fetchExams();
    fetchQuestions();
  }, [pagination.current, pagination.pageSize]);

  const fetchExams = async () => {
    try {
      setLoading(true);
      const response = await api.get('/exams/admin/', {
        params: {
          page: pagination.current,
          per_page: pagination.pageSize
        }
      });

      if (response.data.success) {
        setExams(response.data.data.items);
        setPagination(prev => ({
          ...prev,
          total: response.data.data.total
        }));
      }
    } catch (error) {
      message.error('获取考试列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchQuestions = async () => {
    try {
      const response = await api.get('/questions/admin/', {
        params: { per_page: 1000 }
      });
      if (response.data.success) {
        setQuestions(response.data.data.items);
      }
    } catch (error) {
      message.error('获取题目列表失败');
    }
  };

  const handleCreate = () => {
    setEditingExam(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: Exam) => {
    setEditingExam(record);
    form.setFieldsValue({
      title: record.title,
      description: record.description,
      total_score: record.total_score,
      pass_score: record.pass_score,
      time_limit: record.time_limit,
      question_count: record.question_count,
      is_active: record.is_active
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await api.delete(`/exams/admin/${id}`);
      message.success('删除成功');
      fetchExams();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingExam) {
        await api.put(`/exams/admin/${editingExam.id}`, values);
        message.success('更新成功');
      } else {
        await api.post('/exams/admin/', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchExams();
    } catch (error) {
      message.error(editingExam ? '更新失败' : '创建失败');
    }
  };

  const handlePreview = (record: Exam) => {
    setPreviewingExam(record);
    setPreviewModalVisible(true);
  };

  const columns = [
    {
      title: '考试标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      render: (text: string) => (
        <div style={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {text}
        </div>
      )
    },
    {
      title: '总分',
      dataIndex: 'total_score',
      key: 'total_score',
      width: 80
    },
    {
      title: '及格分',
      dataIndex: 'pass_score',
      key: 'pass_score',
      width: 80
    },
    {
      title: '时长(分钟)',
      dataIndex: 'time_limit',
      key: 'time_limit',
      width: 100
    },
    {
      title: '题目数',
      dataIndex: 'question_count',
      key: 'question_count',
      width: 80,
      render: (count: number, record: Exam) => (
        <Button type="link" onClick={() => navigate(`/exams/${record.id}/questions`)}>{count}</Button>
      )
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 80,
      render: (active: boolean) => (
        <Tag color={active ? 'green' : 'red'}>
          {active ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date: string) => new Date(date).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: Exam) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handlePreview(record)}
          >
            预览
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个考试吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card title="考试管理" extra={
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          新建考试
        </Button>
      }>
        <Table
          columns={columns}
          dataSource={exams}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
          }}
          onChange={(pagination) => {
            setPagination(prev => ({
              ...prev,
              current: pagination.current || 1,
              pageSize: pagination.pageSize || 10
            }));
          }}
        />
      </Card>

      <Modal
        title={editingExam ? '编辑考试' : '新建考试'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="title"
            label="考试标题"
            rules={[{ required: true, message: '请输入考试标题' }]}
          >
            <Input placeholder="请输入考试标题" />
          </Form.Item>

          <Form.Item
            name="description"
            label="考试描述"
          >
            <TextArea rows={3} placeholder="请输入考试描述" />
          </Form.Item>

          <Form.Item
            name="total_score"
            label="总分"
            rules={[{ required: true, message: '请输入总分' }]}
          >
            <InputNumber min={1} max={1000} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="pass_score"
            label="及格分数"
            rules={[{ required: true, message: '请输入及格分数' }]}
          >
            <InputNumber min={1} max={1000} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="time_limit"
            label="考试时长(分钟)"
            rules={[{ required: true, message: '请输入考试时长' }]}
          >
            <InputNumber min={1} max={480} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="question_count"
            label="题目数量"
            rules={[{ required: true, message: '请输入题目数量' }]}
          >
            <InputNumber min={1} max={100} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="is_active"
            label="启用状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingExam ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="考试预览"
        open={previewModalVisible}
        onCancel={() => setPreviewModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setPreviewModalVisible(false)}>
            关闭
          </Button>,
          <Button key="manage" type="primary" onClick={() => {
            if (previewingExam) {
              navigate(`/exams/${previewingExam.id}/questions`);
            }
          }}>
            管理题目
          </Button>
        ]}
        width={800}
      >
        {previewingExam && (
          <div>
            <h3>{previewingExam.title}</h3>
            <p><strong>描述：</strong>{previewingExam.description || '无'}</p>
            <div style={{ display: 'flex', gap: '20px', marginBottom: '16px' }}>
              <span><strong>总分：</strong>{previewingExam.total_score}</span>
              <span><strong>及格分：</strong>{previewingExam.pass_score}</span>
              <span><strong>时长：</strong>{previewingExam.time_limit}分钟</span>
              <span><strong>题目数：</strong>{previewingExam.question_count}</span>
            </div>
            <div style={{ display: 'flex', gap: '20px' }}>
              <span><strong>状态：</strong>
                <Tag color={previewingExam.is_active ? 'green' : 'red'}>
                  {previewingExam.is_active ? '启用' : '禁用'}
                </Tag>
              </span>
              <span><strong>创建时间：</strong>{new Date(previewingExam.created_at).toLocaleString()}</span>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ExamManagement; 